import sun.reflect.generics.tree.Tree;

import java.util.*;
import java.util.regex.Pattern;

/**
 * @author : zzr
 * @description : 二叉树创建学习
 * @date :
 */
public class BinaryTree {
    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    public TreeNode root; //将来这个引用 指向的就是根结点

    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        B.left = D;
        B.right = E;
        E.right = H;
        A.right = C;
        C.left = F;
        C.right = G;

        return A;
    }

    /**
     * 前序遍历
     *
     * @param root
     */
    public void preOrder(TreeNode root) {
        if (root == null) return;

        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);

    }

    /**
     * 二叉树中序遍历
     *
     * @param root
     */
    public void inOrder(TreeNode root) {
        if (root == null) return;

        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }

    /**
     * 二叉树后序遍历
     *
     * @param root
     */
    public void postOrder(TreeNode root) {
        if (root == null) return;

        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }

    /**
     * 将前序遍历的结果 存储到list中
     *
     * @param root
     * @return
     */
    List<TreeNode> ret = new ArrayList<>();

    public List<TreeNode> preOrder2(TreeNode root) {
        if (root == null) return ret;
        ret.add(root);
        preOrder2(root.left);
        preOrder2(root.right);
        return ret;
    }

    /**
     * 将前序遍历的结果 存储到list中
     *
     * @param root
     * @return
     */
    public List<TreeNode> perOrder3(TreeNode root) {
        List<TreeNode> ret = new ArrayList<>();
        if (root == null) return ret;

        ret.add(root);

        List<TreeNode> leftTree = perOrder3(root.left);
        ret.addAll(leftTree);

        List<TreeNode> rightTree = perOrder3(root.right);
        ret.addAll(rightTree);

        return ret;
    }

    /**
     * 将中序遍历的结果 存储在List中
     *
     * @param root
     * @return
     */
    public List<TreeNode> inOrder2(TreeNode root) {
        List<TreeNode> ret = new ArrayList<>();

        if (root == null) return ret;

        List<TreeNode> leftTree = inOrder2(root.left);
        ret.addAll(leftTree);

        ret.add(root);

        List<TreeNode> rightTree = inOrder2(root.right);
        ret.addAll(rightTree);

        return ret;
    }

    /**
     * 将后序遍历的结果存储在list中
     *
     * @param root
     * @return
     */
    public List<TreeNode> postOrder2(TreeNode root) {
        List<TreeNode> ret = new ArrayList<>();
        if (root == null) return ret;

        List<TreeNode> leftTree = postOrder2(root.left);
        ret.addAll(leftTree);

        List<TreeNode> rightTree = postOrder2(root.right);
        ret.addAll(rightTree);

        ret.add(root);

        return ret;
    }


    public int size = 0;

    /**
     * 二叉树元素计数
     *
     * @param root
     * @return
     */
    public int nodeSize(TreeNode root) {
        if (root == null) return size;
        size++;
        nodeSize(root.left);
        nodeSize(root.right);
        return size;
    }

    public int nodeSize2(TreeNode root) {
        int size = 0;
        if (root == null) return size;

        int leftSize = nodeSize2(root.left);
        int rightSize = nodeSize2(root.right);

        return leftSize + rightSize + 1;
    }

    int leaveSize = 0;

    /**
     * 获得二叉树的叶子结点个数
     *
     * @param root
     * @return
     */
    public int getLeaveSize(TreeNode root) {
        if (root == null) return 0;

        if (root.right == null && root.left == null) {
            leaveSize++;
        }
        getLeaveSize(root.left);
        getLeaveSize(root.right);

        return leaveSize;
    }

    public int getLeaveSize2(TreeNode root) {
        int leaveSize = 0;
        if (root == null) return leaveSize;

        if (root.left == null && root.right == null) {
            return 1;
        }

        int leftLeaveSize = getLeaveSize2(root.left);
        int rightLeaveSize = getLeaveSize2(root.right);

        return leftLeaveSize + rightLeaveSize;
    }

    /**
     * 获得二叉树第K层的结点个数
     *
     * @param root
     * @param k
     * @return
     */
    public int getKLevelNodeCount(TreeNode root, int k) {
        int count = 0;
        if (root == null) return count;
        if (k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left, k - 1) + getKLevelNodeCount(root.right, k - 1);
    }

    /**
     * 获得二叉树的高度
     *
     * @param root
     * @return
     */
    public int getTreeHeight(TreeNode root) {
        if (root == null) return 0;
        int leftTreeHeight = getTreeHeight(root.left);
        int rightTreeHeight = getTreeHeight(root.right);
        return leftTreeHeight > rightTreeHeight ? leftTreeHeight + 1 : rightTreeHeight + 1;
    }

    /**
     * 根据先序遍历，遍历根为root的二叉树查找是否有值为value的元素
     *
     * @param root
     * @param value
     * @return
     */
    public boolean find(TreeNode root, char value) {
        if (root == null) return false;

        if (root.val == value) {
            return true;
        }
        boolean leftFlg = find(root.left, value);
        if (leftFlg == true) {
            return true;
        }
        boolean rightFlg = find(root.right, value);
        if (rightFlg == true) {
            return true;
        }
        return false;
    }

    /**
     * 判断两棵树是否相同
     *
     * @param p
     * @param q
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {

        //如果两棵树中，一棵为空，另一课非空，则一定不相同
        if ((p != null && q == null) || (p == null && q != null)) {
            return false;
        }

        //如果两棵树均为空，则相同
        if (p == null && q == null) {
            return true;
        }

        //代码执行到这里，两棵树一定都不为null
        if (p.val != q.val) {
            return false;
        }

        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    /**
     * 判断root树中是否包含subRoot树
     *
     * @param root
     * @param subRoot
     * @return
     */
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {

        if (root == null) {
            return false;
        }

        if (isSameTree(root, subRoot)) {
            return true;
        }

        if (isSubtree(root.left, subRoot)) {
            return true;
        }

        if (isSubtree(root.right, subRoot)) {
            return true;
        }

        return false;
    }

    /**
     * 反转二叉树
     *
     * @param root
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;

        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }


    public int getHeight(TreeNode root) {
        if (root == null) return 0;

        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        if (leftHeight >= 0 && rightHeight >= 0 &&
                Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight, rightHeight) + 1;
        } else {
            return -1;
        }
    }

    /**
     * 判断二叉树是否为平衡二叉树
     *
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;

        return getHeight(root) > 0;
    }


    /**
     * 对称二叉树的判断
     *
     * @param root
     * @return
     */
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;

        return isSymmetricChild(root.left, root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree, TreeNode rightTree) {
        if ((leftTree == null && rightTree != null) || (leftTree != null && rightTree == null)) {
            return false;
        }

        if (leftTree == null && rightTree == null) {
            return true;
        }

        if (leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricChild(leftTree.left, rightTree.right) && isSymmetricChild(leftTree.right, rightTree.left);
    }


    public static int i = 0;

    /**
     * 创建一棵二叉树
     *
     * @param str
     * @return
     */
    public static TreeNode creatrTree(String str) {
        TreeNode root = null;

        if (str.charAt(i) != '#') {
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = creatrTree(str);
            root.right = creatrTree(str);
        } else {
            i++;
        }
        return root;
    }

    /**
     * 二叉树层序遍历
     *
     * @param root
     */
    public void levelOrder(TreeNode root) {
        if (root == null) return;
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode cur = null;
        queue.offer(root);
        while (!queue.isEmpty()) {
            cur = queue.poll();
            System.out.print(cur.val + " ");

            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }

    /**
     * 二叉树的层序遍历2
     *
     * @param root
     * @return
     */
    public List<List<TreeNode>> levelOrder2(TreeNode root) {
        List<List<TreeNode>> ret = new ArrayList<>();
        if (root == null) return ret;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            //求一下当前队列的大小
            int size = queue.size();

            List<TreeNode> tmp = new ArrayList<>();
            while (size != 0) {
                //出队size次，就相当于把这一次的结点都出队了
                TreeNode cur = queue.poll();
                tmp.add(cur);
                size--; //出队一个size减减一次
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            ret.add(tmp);
        }
        return ret;
    }

    /**
     * 判断二叉树是否是完全二叉树
     *
     * @param root
     * @return
     */
    public boolean isCompleteTree(TreeNode root) {
        if (root == null) return true;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                //此时遇到null
                break;
            }
        }

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                return false;
            }
        }
        return true;
    }

    /**
     * 查找根结点为root的二叉树中，参数p和q的公共祖先结点
     *
     * @param root
     * @param p
     * @param q
     * @return
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;

        if (root == p || root == q) {
            return root;
        }

        TreeNode leftTree = lowestCommonAncestor(root.left, p, q);
        TreeNode rightTree = lowestCommonAncestor(root.right, p, q);

        if (leftTree != null && rightTree != null) {
            return root;
        } else if (leftTree != null) {
            return leftTree;
        } else {
            return rightTree;
        }
    }

    /**
     * 找到root 到 node 之间 路径 上的 所有 的 结点，存储在stack中
     *
     * @param root
     * @param node
     * @param stack
     * @return
     */
    private boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if (root == null || node == null) {
            return false;
        }
        stack.push(root);
        if (root == node) {
            return true;
        }
        boolean flg = getPath(root.left, node, stack);
        if (flg) {
            return true;
        }
        boolean flg2 = getPath(root.right, node, stack);
        if (flg2) {
            return true;
        }
        stack.pop();
        return false;
    }

    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;

        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();

        getPath(root, p, stackP);
        getPath(root, q, stackQ);

        int siezP = stackP.size();
        int siezQ = stackQ.size();

        if (siezP > siezQ) {
            int size = siezP - siezQ;
            while (size != 0) {
                stackP.pop();
                size--;
            }
        } else {
            int size = siezQ - siezP;
            while (size != 0) {
                stackQ.pop();
                size--;
            }
        }

        while (!stackP.isEmpty() && !stackQ.isEmpty()) {
            if (stackP.peek().equals(stackQ.peek())) {
                return stackP.peek();
            }
            stackP.pop();
            stackQ.pop();
        }
        return null;
    }
/*

     // 根据先序遍历和中序遍历创建二叉树

    public int priIndex;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder, inorder, 0, inorder.length - 1);
    }

    private TreeNode buildTreeChild(int[] preorder, int[] inorder, int inbegin, int inend) {

        //1. 没有左子树 或者 没有右子树
        if (inbegin > inend) {
            return null;
        }

        //2.创建根结点
        TreeNode root = new TreeNode(preorder[priIndex]);

        //3.从中序遍历当中 找到前序遍历中priIndexx所在的根结点的下标
        int rootIndex = findIndex(inorder, inbegin, inend, preorder[priIndex]);
        if (-1 == rootIndex) {
            return null;
        }

        priIndex++;

        //创建左右子树
        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex - 1);
        root.right = buildTreeChild(preorder,inorder,rootIndex + 1,inend);

        return root;
    }

    private int findIndex(int[] inorder, int inbegin, int inend, int key) {
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
  
 */

    /*
    //根据后序遍历和中序遍历构建二叉树

    class Solution {
        public int postIndex;
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            postIndex = postorder.length - 1;
            return buildTreeChild(postorder,inorder,0,postorder.length - 1);
        }

        private TreeNode buildTreeChild(int[] postorder, int[] inorder, int inbegin, int inend) {

            //1. 没有左子树 或者 没有右子树
            if(inbegin > inend) {
                return null;
            }

            //2.创建根结点
            TreeNode root = new TreeNode(postorder[postIndex]);

            //3.从中序遍历当中 找到后序遍历中postIndex所在的根结点的下标
            int rootIndex = findIndex(inorder, inbegin, inend, postorder[postIndex]);

            postIndex--;

            //创建左右子树
            //注意！此处要先创建右树再创建左树
            //因为后序遍历的顺序是左右根，再根据后序遍历反推二叉树的时候，是从后面遍历后序遍历的即先根再右最后左
            root.right = buildTreeChild(postorder, inorder, rootIndex + 1, inend);
            root.left = buildTreeChild(postorder, inorder, inbegin, rootIndex - 1);

            return root;
        }

        private int findIndex(int[] inorder, int inbegin, int inend, int key) {
            for(int i = inbegin; i <= inend; i++) {
                if(inorder[i] == key) {
                    return i;
                }
            }
            return -1;
        }
    }

     */

    /**
     * 前序遍历 非递归实现
     * @param root
     */
    public void preOrderNor(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();

        TreeNode cur = root;
        TreeNode top = null;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }

            top = stack.pop();
            cur = top.right;
        }
    }

    /**
     * 中序非递归遍历
     * @param root
     */
    public void inOrderNor(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();

        TreeNode cur = root;
        TreeNode top = null;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.pop();
            System.out.print(top.val + " ");
            cur = top.right;
        }
    }

    /**
     * 后序非递归遍历
     * @param root
     */
    public void postOrderNor(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();

        TreeNode cur = root;
        TreeNode top = null;
        TreeNode prev = null;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            //  不能直接弹出 否则会找不到右边元素
            top = stack.peek();
            //右边为空 或者右边已经打印过 就可以打印当前结点
            if(top.right == null || top.right == prev) {
                stack.pop();
                System.out.print(top.val + " ");
                prev = top;
            } else {
                cur = top.right;
            }
        }
    }
}